package kr.hkit.androidcomplete01.ch17;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.MotionEvent;
import android.view.View;

public class SaveCurve2 extends Activity {
	
	private MyView vw;
	ArrayList<Vertex> arVertex;
	int count;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		vw = new MyView(this);
		setContentView(vw);
		
		if(savedInstanceState==null){
			arVertex = new ArrayList<Vertex>();
		}else{
			arVertex = savedInstanceState.getParcelableArrayList("Curve");
		}
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelableArrayList("Curve", arVertex);
	}
	
	
	protected class MyView extends View {
		Paint mPaint;

		public MyView(Context context) {
			super(context);
			// Paint객체 미리 초기화
			mPaint = new Paint();
			mPaint.setColor(Color.BLACK); // 수정
			mPaint.setStrokeWidth(3);
			mPaint.setAntiAlias(true);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawColor(Color.LTGRAY);

			for (int i = 0; i < arVertex.size(); i++) {
				if (arVertex.get(i).isDraw) {
					canvas.drawLine(arVertex.get(i - 1).x,
							arVertex.get(i - 1).y, arVertex.get(i).x,
							arVertex.get(i).y, mPaint);
				}
			}
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			super.onTouchEvent(event);

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				arVertex.add(new Vertex(event.getX(), event.getY(), false));
				return true;
			}
			if (event.getAction() == MotionEvent.ACTION_MOVE) {
				arVertex.add(new Vertex(event.getX(), event.getY(), true));
				invalidate();
				return true;
			}
			return false;
		}

	}

}

class Vertex implements Parcelable{
	
	float x;
	float y;
	boolean isDraw;
	
	
	public Vertex(float x, float y, boolean isDraw) {
		super();
		this.x = x;
		this.y = y;
		this.isDraw = isDraw;
	}
	

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeFloat(x);
		dest.writeFloat(y);
		dest.writeBooleanArray(new boolean[]{isDraw});
	}
	
	
	public static final Parcelable.Creator<Vertex> CREATOR = new Creator<Vertex>() {

		@Override
		public Vertex createFromParcel(Parcel source) {
			int x = source.readInt();
			int y = source.readInt();
			boolean[] td = new boolean[1];
			source.readBooleanArray(td);
			
			return new Vertex(x, y, td[0]);
		}

		@Override
		public Vertex[] newArray(int size) {
			return new Vertex[size];
		}
	};
	
}
